package jgs1904.realm;

import jgs1904.pojo.User;
import jgs1904.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyRealm extends AuthorizingRealm {

    // 声明业务层属性
    @Autowired
    private UserService userService;


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证开始");
        // 获取用户的登录名
        String uname = token.getPrincipal().toString();
        // 根据用户名从数据库获取用户信息
        User user = userService.selUserInfoService(uname);

        if (user != null) {
            // 校验密码
            AuthenticationInfo info = new SimpleAuthenticationInfo(token.getPrincipal(), user.getPwd(), ByteSource.Util.bytes("salt"), token.getPrincipal().toString());
            return info;
        }

        return null;
    }


    /**
     * 授权
     *
     * @param principalCollection the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("开始授权");
        //0.获取当前认证的用户的身份信息(登录名)
        String uname = (String) principalCollection.getPrimaryPrincipal();
        //模拟数据查询权限
//        List<String> authorities = new ArrayList<>();
//        authorities.add("user:del");
//        authorities.add("user:edit");

        //1.查询当前用户具备的权限信息--从数据库
        List<String> list = userService.selPowerInfoService(uname);
        //查询当前用户的角色信息
        List<String> list2 = userService.selRoleInfoService(uname);

        //2.将当前用户具备的权限信息给Shiro
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //添加权限
        info.addStringPermissions(list);
        //添加角色
        info.addRoles(list2);

        //3.返回
        return info;
    }

}
